<script setup lang="ts">
import { reactive, ref } from 'vue';
import { NButton, NCol, NForm, NFormItem, NInput, NModal, NRow, useMessage } from 'naive-ui';

// 创建消息实例
const message = useMessage();

// 移除了vLoading指令注册代码

// 定义组件属性
interface Props {
  show?: boolean;
  hasEmail?: boolean;
  email?: string;
  loading?: boolean;
}

// 定义组件事件
interface Emits {
  (e: 'update:show', value: boolean): void;
  (
    e: 'confirm',
    formData: {
      email: string;
      captcha: string;
      emailCode: string;
    }
  ): void;
}

// 组件属性和事件
const _props = withDefaults(defineProps<Props>(), {
  show: false,
  hasEmail: false,
  email: '',
  loading: false
});

const emit = defineEmits<Emits>();

// 表单数据
const emailForm = reactive({
  email: '',
  captcha: '',
  emailCode: ''
});

// 表单引用
const emailFormRef = ref<InstanceType<typeof NForm>>();

// 验证码相关
const emailCaptchaUrl = ref('');
const refreshingEmailCaptcha = ref(false);
const emailCaptchaError = ref('');
const emailCodeError = ref('');
const emailCountDown = ref(0);

// 验证规则
const emailRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  captcha: [{ required: true, message: '请输入图形验证码', trigger: 'blur' }],
  emailCode: [
    { required: true, message: '请输入邮箱验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
  ]
};

// 刷新验证码
const refreshCaptcha = async () => {
  refreshingEmailCaptcha.value = true;
  emailCaptchaError.value = '';

  try {
    // 模拟获取验证码图片
    // const response = await getEmailCaptcha();
    // emailCaptchaUrl.value = response.url;

    // 模拟验证码图片URL
    emailCaptchaUrl.value = `data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='40' viewBox='0 0 120 40'%3E%3Crect width='120' height='40' fill='%23f5f5f5'/%3E%3Ctext x='60' y='25' font-family='Arial' font-size='20' text-anchor='middle' fill='%23333'%3EXYZ789%3C/text%3E%3C/svg%3E?timestamp=${Date.now()}`;
  } catch {
    message.error('验证码加载失败，请重试');
  } finally {
    refreshingEmailCaptcha.value = false;
  }
};

// 处理验证码错误
const handleCaptchaError = () => {
  emailCaptchaError.value = '验证码加载失败';
};

// 发送邮箱验证码
const sendEmailCode = async () => {
  emailCodeError.value = '';

  // 验证邮箱和图形验证码
  if (!emailForm.email) {
    message.error('请输入邮箱');
    return;
  }
  if (!emailForm.captcha) {
    message.error('请输入图形验证码');
    return;
  }

  try {
    // 模拟发送请求
    // await sendEmailCodeApi(emailForm.email, emailForm.captcha);

    message.success('验证码已发送至您的邮箱');

    // 开始倒计时
    emailCountDown.value = 60;
    const timer = setInterval(() => {
      emailCountDown.value -= 1;
      if (emailCountDown.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  } catch {
    emailCodeError.value = '发送失败，请重试';
    message.error('发送失败，请检查验证码是否正确');
  }
};

// 确认绑定
const handleConfirm = async () => {
  if (!(await emailFormRef.value?.validate())) return;
  emit('confirm', { ...emailForm });
};

// 重置表单
const resetForm = () => {
  emailForm.email = '';
  emailForm.captcha = '';
  emailForm.emailCode = '';
  emailCaptchaError.value = '';
  emailCodeError.value = '';
  emailCountDown.value = 0;
  refreshCaptcha();
};

// 关闭弹窗
const handleClose = () => {
  emit('update:show', false);
  setTimeout(() => {
    resetForm();
  }, 300);
};

// 组件挂载时刷新验证码
refreshCaptcha();
</script>

<template>
  <NModal
    :show="show"
    :title="hasEmail ? '更换邮箱' : '绑定邮箱'"
    preset="dialog"
    :close-on-esc="true"
    :close-on-click-overlay="false"
    :focus-lock="true"
    @update:show="value => emit('update:show', value)"
    @close="handleClose"
  >
    <NForm ref="emailFormRef" :model="emailForm" :rules="emailRules">
      <NFormItem label="邮箱" path="email">
        <NInput v-model:value="emailForm.email" placeholder="请输入邮箱" />
      </NFormItem>
      <NFormItem label="图形验证码" path="captcha" :error="emailCaptchaError">
        <NRow :gutter="16">
          <NCol :span="14">
            <NInput
              v-model:value="emailForm.captcha"
              placeholder="请输入图形验证码"
              :status="emailCaptchaError ? 'error' : undefined"
            />
          </NCol>
          <NCol :span="10">
            <div class="captcha-image" :class="{ loading: refreshingEmailCaptcha }" @click="refreshCaptcha">
              <img v-if="emailCaptchaUrl" :src="emailCaptchaUrl" alt="验证码" @error="handleCaptchaError" />
              <span v-else class="captcha-loading">加载中...</span>
              <span class="captcha-refresh-icon" @click.stop="refreshCaptcha">↻</span>
            </div>
          </NCol>
        </NRow>
      </NFormItem>
      <NFormItem label="邮箱验证码" path="emailCode" :error="emailCodeError">
        <NRow :gutter="16">
          <NCol :span="14">
            <NInput
              v-model:value="emailForm.emailCode"
              placeholder="请输入邮箱验证码"
              :status="emailCodeError ? 'error' : undefined"
            />
          </NCol>
          <NCol :span="10">
            <NButton
              type="primary"
              :disabled="!emailForm.email || !emailForm.captcha || emailCountDown > 0"
              :loading="loading"
              @click="sendEmailCode"
            >
              {{ emailCountDown > 0 ? `${emailCountDown}秒后重新发送` : '发送验证码' }}
            </NButton>
          </NCol>
        </NRow>
      </NFormItem>
    </NForm>
    <template #footer>
      <NButton @click="handleClose">取消</NButton>
      <NButton type="primary" :loading="loading" @click="handleConfirm">确认</NButton>
    </template>
  </NModal>
</template>

<style scoped lang="scss">
// 验证码样式
.captcha-image {
  width: 100%;
  height: 40px;
  cursor: pointer;
  overflow: hidden;
  border-radius: 6px;
  background: #f5f5f5;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  border: 1px solid #e8e8e8;

  &:hover {
    background: #e8e8e8;
    transform: scale(1.02);
    border-color: #1890ff;
  }

  &:active {
    transform: scale(0.98);
  }

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .captcha-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #666;
    font-size: 14px;
  }

  .captcha-refresh-icon {
    position: absolute;
    right: 8px;
    bottom: 4px;
    font-size: 16px;
    color: #999;
    cursor: pointer;
    opacity: 0.7;
    transition: all 0.3s ease;

    &:hover {
      color: #1890ff;
      opacity: 1;
      transform: rotate(180deg);
    }
  }
}

// 验证码加载中样式
[v-loading] {
  opacity: 0.6;
}

// 弹窗样式修复
.n-modal {
  &:deep(.n-modal__overlay) {
    background-color: rgba(0, 0, 0, 0.5) !important;
  }

  &:deep(.n-modal__content) {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 24px rgba(0, 0, 0, 0.15);
  }
}

// 表单样式
.n-form-item {
  margin-bottom: 24px;

  &__label {
    font-weight: 500;
    color: #333;
    font-size: 14px;
  }
}

.n-input {
  border-radius: 6px;

  &:focus {
    border-color: #1890ff;
    box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.15);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .captcha-image {
    height: 36px;
  }

  .n-form-item {
    margin-bottom: 20px;
  }
}
</style>
